#include "config.h"
#include "Arduino.h"

const char* weather_host = "api.seniverse.com";
const char* weather_path = "/v3/weather/daily.json";
const char* weather_location = "hangzhou";
const char* weather_key = "S29tX0lKJkMZj5kk4";

// 监听本地UDP数据包端口
unsigned int localPort = 2390;

WiFiUDP udp;
WiFiClient client;

String* sc1GetWeather() {
  DynamicJsonDocument jsonBuffer(4096);
  DynamicJsonDocument result = updateWeather(jsonBuffer);
  if (result.isNull()) return nullptr;

  // 获取 results 数组
  JsonArray results = result["results"];
  // 获取第一个结果对象
  JsonObject dailyData = results[0]["daily"][0];

  // 动态分配 String 数组并返回指针
  String* weatherData = new String[6];
  weatherData[0] = dailyData["text_day"].as<String>();
  weatherData[1] = dailyData["code_day"].as<String>();
  weatherData[2] = dailyData["text_night"].as<String>();
  weatherData[3] = dailyData["code_night"].as<String>();
  weatherData[4] = dailyData["high"].as<String>();
  weatherData[5] = dailyData["low"].as<String>();

  return weatherData;
}

DynamicJsonDocument updateWeather(DynamicJsonDocument& jsonBuffer) {
  if (client.connect(weather_host, 80) == 1) {
    Serial.println("Connection successful");
    Serial.print("设备IP地址: ");
    Serial.println(WiFi.localIP());
    Serial.println("开启UDP通信");
    udp.begin(localPort);
    Serial.print("本地端口为: ");
    Serial.println(localPort);
    String url = String(weather_path) + "?location=" + weather_location + "&key=" + weather_key + "&language=zh-Hans&start=0&days=3";
    client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + weather_host + "\r\n" + "Connection: close\r\n\r\n");
    Serial.println(url);
    unsigned long timeout = millis();
    while (client.available() == 0) {
      if (millis() - timeout > 5000) {
        Serial.println("Request timed out");
        client.stop();
        return DynamicJsonDocument(0);
      }
    }
    String response;
    while (client.available()) {
      response = client.readStringUntil('\r');
    }
    // Serial.println(response);
    // 创建一个 JsonBuffer 用于解析 JSON 数据
    DynamicJsonDocument jsonBuffer(4096);
    // 解析 JSON 数据
    DeserializationError error = deserializeJson(jsonBuffer, response);
    if (error) {
      Serial.print(F("JSON 解析失败："));
      Serial.println(error.c_str());
      return DynamicJsonDocument(0);
    }
    return jsonBuffer;
  } else {
    Serial.println("Failed to connect to weather API");
    delay(5000);
    return DynamicJsonDocument(0);
  }
}

String* scWeGetWeather() {
  DynamicJsonDocument jsonBuffer(4096);
  DynamicJsonDocument result = updateWeather(jsonBuffer);
  if (result.isNull()) return nullptr;
  Serial.println("scWeGetWeather开始工作");
  // 获取 results 数组
  JsonArray results = result["results"];
  // 获取第一个结果对象
  JsonObject dailyData = results[0]["daily"][0];

  // 动态分配 String 数组并返回指针
  String* weatherData = new String[30];
  weatherData[0] = dailyData["text_day"].as<String>();
  weatherData[1] = dailyData["text_night"].as<String>();
  weatherData[2] = dailyData["rainfall"].as<String>();
  weatherData[3] = dailyData["precip"].as<String>();
  weatherData[4] = dailyData["wind_direction"].as<String>();
  weatherData[5] = dailyData["wind_speed"].as<String>();

  for (int i = 0; i < 3; ++i) {
    JsonObject futureData = results[0]["daily"][i];
    int index = 6 + i * 4;
    weatherData[index] = futureData["text_day"].as<String>();
    weatherData[index + 1] = futureData["code_day"].as<String>();
    weatherData[index + 2] = futureData["high"].as<String>();
    weatherData[index + 3] = futureData["low"].as<String>();
  }
  Serial.println("返回weatherData");
  return weatherData;
}

void printScWeWeatherData(String* weatherData) {
  if (weatherData == nullptr) {
    Serial.println("Weather data is nullptr");
    return;
  }
  Serial.println("Weather Data:");
  Serial.println("-------------");
  
  Serial.println("Today:");
  Serial.print("Day: "); Serial.println(weatherData[0]);
  Serial.print("Night: "); Serial.println(weatherData[1]);
  Serial.print("Rainfall: "); Serial.println(weatherData[2]);
  Serial.print("Precipitation: "); Serial.println(weatherData[3]);
  Serial.print("Wind Direction: "); Serial.println(weatherData[4]);
  Serial.print("Wind Speed: "); Serial.println(weatherData[5]);

  Serial.println("Next 3 Days:");
  for (int i = 0; i < 3; ++i) {
    int index = 6 + i * 4;
    Serial.print("Day: "); Serial.println(weatherData[index]);
    Serial.print("Day Code: "); Serial.println(weatherData[index + 1]);
    Serial.print("high: "); Serial.println(weatherData[index + 2]);
    Serial.print("low: "); Serial.println(weatherData[index + 3]);
  }
  
  Serial.println("-------------");
}

#ifdef _SQUARELINE_PROJECT_UI_H
void scWeatherUpdate(){
  float *dht11Data=new float[2];
  dht11Data=getDHTdata();
  if(dht11Data==nullptr){
    Serial.println("dht11 data is nullptr");
    return; 
  }
  String* weatherData=scWeGetWeather();
    if (weatherData == nullptr) {
    Serial.println("Weather data is nullptr");
    return;
  }
  
  lv_label_set_text(ui_ScWeTempAndHum, (String(int(dht11Data[1])) + "'C/" + String(int(dht11Data[0])) + "%").c_str());
  lv_label_set_text(ui_ScWePrecipitation, (weatherData[2] + "mm\n" + weatherData[3] + "%").c_str());
  lv_label_set_text(ui_ScWeWeedSpeed, (weatherData[4] + "\n风速" + weatherData[5] + "m/s").c_str());
  lv_label_set_text(ui_ScWeWeToday, ("白天 " + weatherData[0] + "\n夜晚 " + weatherData[1]).c_str());
  lv_label_set_text(ui_ScWeTemp0, (weatherData[9] + "'C-" + weatherData[8] + "'C").c_str());
  lv_label_set_text(ui_ScWeTemp1, (weatherData[13] + "'C-" + weatherData[12] + "'C").c_str());
  lv_label_set_text(ui_ScWeTemp2, (weatherData[17] + "'C-" + weatherData[16] + "'C").c_str());
  lv_label_set_text(ui_ScWeWe0, weatherData[6].c_str());
  lv_label_set_text(ui_ScWeWe1, weatherData[10].c_str());
  lv_label_set_text(ui_ScWeWe2, weatherData[14].c_str());
  lv_img_set_src_for_ScWeather(ui_ScWeWeImage0,weatherData[7].toInt());
  lv_img_set_src_for_ScWeather(ui_ScWeWeImage1,weatherData[11].toInt());
  lv_img_set_src_for_ScWeather(ui_ScWeWeImage2,weatherData[15].toInt());

}

void lv_img_set_src_for_ScWeather(lv_obj_t *ui,int n){
  if(n==0){
    lv_img_set_src(ui, &ui_img_while_scw0_png);
    return ;
  }else if(n==1){
    lv_img_set_src(ui, &ui_img_while_scw1_png);
    return ;
  }else if(n==2){
    lv_img_set_src(ui, &ui_img_while_scw2_png);
    return ;
  }else if(n==3){
    lv_img_set_src(ui, &ui_img_while_scw3_png);
    return ;
  }else if(n==4){
    lv_img_set_src(ui, &ui_img_while_scw4_png);
    return ;
  }else if(n==5){
    lv_img_set_src(ui, &ui_img_while_scw5_png);
    return ;
  }else if(n==6){
    lv_img_set_src(ui, &ui_img_while_scw6_png);
    return ;
  }else if(n==7){
    lv_img_set_src(ui, &ui_img_while_scw7_png);
    return ;
  }else if(n==8){
    lv_img_set_src(ui, &ui_img_while_scw8_png);
    return ;
  }else if(n==9){
    lv_img_set_src(ui, &ui_img_while_scw9_png);
    return ;
  }else if(n==10){
    lv_img_set_src(ui, &ui_img_while_scw10_png);
    return ;
  }else if(n==11){
    lv_img_set_src(ui, &ui_img_while_scw11_png);
    return ;
  }else if(n==12){
    lv_img_set_src(ui, &ui_img_while_scw12_png);
    return ;
  }else if(n==13){
    lv_img_set_src(ui, &ui_img_while_scw13_png);
    return ;
  }else if(n==14){
    lv_img_set_src(ui, &ui_img_while_scw14_png);
    return ;
  }else if(n==15){
    lv_img_set_src(ui, &ui_img_while_scw15_png);
    return ;
  }else if(n==16){
    lv_img_set_src(ui, &ui_img_while_scw16_png);
    return ;
  }else if(n==17){
    lv_img_set_src(ui, &ui_img_while_scw17_png);
    return ;
  }else if(n==18){
    lv_img_set_src(ui, &ui_img_while_scw18_png);
    return ;
  }else if(n==19){
    lv_img_set_src(ui, &ui_img_while_scw19_png);
    return ;
  }else if(n==20){
    lv_img_set_src(ui, &ui_img_while_scw20_png);
    return ;
  }else if(n==21){
    lv_img_set_src(ui, &ui_img_while_scw21_png);
    return ;
  }else if(n==22){
    lv_img_set_src(ui, &ui_img_while_scw22_png);
    return ;
  }else if(n==23){
    lv_img_set_src(ui, &ui_img_while_scw23_png);
    return ;
  }else if(n==24){
    lv_img_set_src(ui, &ui_img_while_scw24_png);
    return ;
  }else if(n==25){
    lv_img_set_src(ui, &ui_img_while_scw25_png);
    return ;
  }else if(n==26){
    lv_img_set_src(ui, &ui_img_while_scw26_png);
    return ;
  }else if(n==27){
    lv_img_set_src(ui, &ui_img_while_scw27_png);
    return ;
  }else if(n==28){
    lv_img_set_src(ui, &ui_img_while_scw28_png);
    return ;
  }else if(n==29){
    lv_img_set_src(ui, &ui_img_while_scw29_png);
    return ;
  }else if(n==30){
    lv_img_set_src(ui, &ui_img_while_scw30_png);
    return ;
  }else if(n==31){
    lv_img_set_src(ui, &ui_img_while_scw31_png);
    return ;
  }else if(n==32){
    lv_img_set_src(ui, &ui_img_while_scw32_png);
    return ;
  }else if(n==33){
    lv_img_set_src(ui, &ui_img_while_scw33_png);
    return ;
  }else if(n==34){
    lv_img_set_src(ui, &ui_img_while_scw34_png);
    return ;
  }else if(n==35){
    lv_img_set_src(ui, &ui_img_while_scw35_png);
    return ;
  }else if(n==36){
    lv_img_set_src(ui, &ui_img_while_scw36_png);
    return ;
  }else if(n==37){
    lv_img_set_src(ui, &ui_img_while_scw37_png);
    return ;
  }else if(n==38){
    lv_img_set_src(ui, &ui_img_while_scw38_png);
    return ;
  }else if(n==99){
    lv_img_set_src(ui, &ui_img_while_scw99_png);
    return ;
  }else{
    return ;
  }
}


#endif